import React, { Component } from 'react';
import { Modal, Input, Cascader, message } from 'antd';
import { addStaffToOrg, updateStaff, batchUpdateStaff } from '@api/organization';
import PropTypes from 'prop-types';
import cn from 'classnames';
import _ from 'lodash';
import '../add-edit-modal/index.less';
import { PHONE_RE, EMAIL_RE } from '@util/constants';
import { ORGANIZATION_RE32 } from '@util/constants';

class AddStaffModal extends Component {
  static propTypes = {
    visible: PropTypes.bool,
    onCancel: PropTypes.func,
    loadStaffList: PropTypes.func,
    loadOrganizationCascaderTree: PropTypes.func
  };
  static treePruning = (rawTree = [], rawPaths = [], id) => {
    if (!id) {
      return _.cloneDeep(rawTree);
    }
    let tree = _.cloneDeep(rawTree),
      paths = _.cloneDeep(rawPaths);
    let tmpChildren = tree;
    while (tmpChildren.length && paths.length) {
      let current = paths.shift();
      let tmpParent = _.find(tmpChildren, i => _.get(i, '_id') === current);
      tmpChildren = _.get(tmpParent, 'children', []);
    }
    let currentIndex = _.findIndex(tmpChildren, i => _.get(i, '_id') === id);
    tmpChildren.splice(currentIndex, 1);
    return tree;
  };

  static getStateFromProps = props => {
    let {
      paths: rawPaths = [],
      // eslint-disable-next-line
      _id: id = '',
      // eslint-disable-next-line
      parent_oid: parentId = ''
    } = _.get(props, 'currentOrg', {});
    const { editRow, batchEditStaffIds } = props;
    if (editRow) {
      rawPaths = [...editRow.orgInfo.paths, editRow.orgInfo._id];
    }
    // 批量编辑
    const isBatchEdit = batchEditStaffIds && batchEditStaffIds.length;
    if (isBatchEdit) {
      rawPaths = [];
    }
    let rawCascaderTree = _.get(props, 'cascaderTree', []);
    let cascaderTree = AddStaffModal.treePruning(rawCascaderTree, rawPaths, id);
    return {
      id: id,
      name: editRow ? editRow.nickname : '',
      phone: editRow ? editRow.telephone : '',
      email: editRow ? editRow.email : '',
      work: editRow ? editRow.job : '',
      parentId,
      paths: rawPaths,
      cascaderTree,
      nameError: '',
      confirmLoading: false,
      editRow,
      isBatchEdit,
      batchEditStaffIds,
      errors: { name: '', email: '', phone: '' }
    };
  };

  constructor(props) {
    super(props);
    this.state = {
      ...AddStaffModal.getStateFromProps(props)
    };
  }

  // eslint-disable-next-line
  UNSAFE_componentWillReceiveProps(nextProps) {
    // eslint-disable-next-line react/prop-types
    if ((!this.props.visible && nextProps.visible) || nextProps.cascaderTree.length > 0) {
      this.setState({
        ...AddStaffModal.getStateFromProps(nextProps)
      });
    }
  }

  onFromValueChange = (e, key) => {
    let value = e.target.value;
    let body = {
      [key]: value,
      [`${key}Error`]: ''
    };
    const setError = (key, value) => {
      this.setState({ errors: { ...this.state.errors, [key]: value } });
    };
    const distKey = {
      name: () => {
        if (value.length < 2) {
          return '名字长度大于2';
        } else if (!ORGANIZATION_RE32.test(value)) {
          return '请输入正确格式的姓名';
        }
        return '';
      },
      email: () => {
        if (!EMAIL_RE.test(value)) {
          return '请输入正确格式的邮箱';
        }
        return '';
      },
      phone: () => {
        if (value && !PHONE_RE.test(value)) {
          return '请输入正确格式的电话';
        }
        return '';
      },
      work: () => {
        return '';
      }
    };
    const error = distKey[key]();
    setError(key, error);
    this.setState(body);
  };

  onParentChange = (parents = []) => {
    let parentId = parents[parents.length - 1],
      update = { paths: parents, parentId };
    this.setState(update);
  };

  submit = () => {
    const {
      name,
      phone,
      email,
      work,
      paths,
      editRow,
      isBatchEdit,
      batchEditStaffIds,
      errors
    } = this.state;
    const curOrgId = paths[paths.length - 1];
    if ((!name || !email || !curOrgId) && !isBatchEdit) {
      message.error('请确保人员信息填写完整!');
      return;
    }
    const findOne = Object.values(errors).find(r => r);
    if (findOne) {
      message.error(findOne);
      return;
    }

    // 判断是编辑还是新加
    const idKey = editRow ? 'staffId' : 'organizationId';
    const request = isBatchEdit ? batchUpdateStaff : editRow ? updateStaff : addStaffToOrg;
    const body = !isBatchEdit
      ? {
          [idKey]: editRow ? editRow._id : curOrgId,
          nickname: name,
          email: email,
          telephone: phone,
          job: work,
          ...(editRow ? { orgId: curOrgId } : {})
        }
      : {
          staffIds: batchEditStaffIds,
          orgId: curOrgId
        };
    if (!body.telephone) {
      delete body.telephone;
    }
    if (!body.job) {
      delete body.job;
    }
    this.setState({ confirmLoading: true });
    request(body)
      .then(res => {
        if (_.get(res, 'data.result', false)) {
          this.props.onCancel();
          this.props.loadStaffList();
          message.success(`${isBatchEdit ? '批量编辑' : editRow ? '编辑' : '新增'}人员成功!`);
          this.props.loadOrganizationCascaderTree();
        }
      })
      .catch(err => {
        message.error(
          _.get(err, 'message', `${isBatchEdit ? '批量编辑' : editRow ? '编辑' : '新增'}人员失败`)
        );
      })
      .finally(() => {
        this.setState({ confirmLoading: false });
      });
  };

  render() {
    const {
      name,
      phone,
      email,
      work,
      paths,
      cascaderTree,
      editRow,
      isBatchEdit,
      confirmLoading
    } = this.state;
    const { visible } = this.props;
    return (
      <Modal
        maskClosable={false}
        visible={visible}
        title={isBatchEdit ? '批量编辑人员' : editRow ? '编辑人员' : '添加人员'}
        onCancel={this.props.onCancel}
        className={cn(
          'no-header-bottom-lines',
          'bottom-center',
          'padding-24',
          'org-c-add-edit-modal'
        )}
        onOk={_.throttle(this.submit, 1000)}
        confirmLoading={confirmLoading}
      >
        <div className="item">
          <label>
            <i style={{ color: 'red' }}>* </i>
            姓名
          </label>
          <Input
            required
            className="item-value"
            placeholder="请输入中文、英文或数字，字符长度不小于2且不超过32位"
            maxLength={32}
            value={name}
            onChange={e => this.onFromValueChange(e, 'name')}
            disabled={isBatchEdit}
          />
        </div>
        {/* {nameError && <p className="name-error">{nameError}</p>} */}
        <div className="item">
          <label>
            <i style={{ color: 'red' }}>* </i>
            所属部门
          </label>
          <Cascader
            value={paths}
            options={cascaderTree}
            className="item-value"
            changeOnSelect
            onChange={this.onParentChange}
            placeholder="选择所属部门"
            fieldNames={{ label: 'name', value: '_id', children: 'children' }}
          />
        </div>

        <div className="item">
          <label>
            <i style={{ color: 'red' }}>* </i>
            邮箱
          </label>
          <Input
            className="item-value"
            placeholder="请输入邮箱账户"
            value={email}
            onChange={e => this.onFromValueChange(e, 'email')}
            disabled={isBatchEdit}
          />
        </div>
        <div className="item">
          <label>
            <i style={{ marginLeft: 10 }}> </i>手机号
          </label>
          <Input
            className="item-value"
            placeholder="请输入11位手机号"
            value={phone}
            onChange={e => this.onFromValueChange(e, 'phone')}
            disabled={isBatchEdit}
          />
        </div>
        <div className="item">
          <label>
            <i style={{ marginLeft: 10 }}> </i>岗位
          </label>
          <Input
            className="item-value"
            placeholder="请输入岗位名称"
            value={work}
            onChange={e => this.onFromValueChange(e, 'work')}
            disabled={isBatchEdit}
          />
        </div>
      </Modal>
    );
  }
}

export default AddStaffModal;
